/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.mulgaraifz.utilities;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date;

import org.apache.log4j.Logger;

import uk.ljmu.mulgaraifz.errorhandling.FileException;

public class GeneralUtilities {
	private static Logger log = Logger.getLogger(GeneralUtilities.class);
	/**
	 * Converts a given inputstream object into its string representation
	 * @param is inputstream object to convert
	 * @return string representation of the inputstream
	 */
	public static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		}
		catch (IOException ex) 
		{
			log.fatal(ex.getMessage());
			ex.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}
	
	
	/**
	 * Transform Http response stream results into string and store them into a file
	 * 
	 * @param responseStream
	 *            : String containing the response data in stream format
	 * @return String containing the full path to the file generated
	 */
	public static String save2file(Reader responseStream, String filename) throws FileException
	{	
		Date fecha = new Date();
		//Create Unique fileName
		String strFecha = fecha.toString().replace(' ', '_');
		BufferedReader bufferedReader = responseStream instanceof BufferedReader 
        ? (BufferedReader) responseStream
        : new BufferedReader(responseStream);
        StringBuffer result = new StringBuffer();
        char[] buffer = new char[1024];
        int charsRead;
               
		try 
		{
			String strFile = filename
			+  strFecha + ".txt";

			FileWriter fstream = new FileWriter(strFile);
			BufferedWriter out = new BufferedWriter(fstream);
			try 
			{
				while ((charsRead = bufferedReader.read(buffer)) != -1) 
				{
		    	   result.append(buffer, 0, charsRead);		    	   
		           out.write(result.toString());
		    	   result = new StringBuffer();
				}	
				//Close the output stream
			    out.close();
			} 
			catch (IOException e) 
			{
				log.fatal(e.getMessage());
			}
			return strFile;
		} 
		catch (Exception ex) 
		{
			log.error("Error: " + ex);
			throw new FileException("Error in save2File: " + ex.getMessage());
		}
	}
}
